import React, { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { Table, Button, Card, Divider, App } from "antd";
import { LibAppView } from "../../../../lib";
import { utils } from "elmer-common";
import type { ColumnsType } from "antd/es/table"

interface ITaskDetailProps {
    task?: string;
    goBack: () => void;
}

const userList = [
    {
        title: "莫鑫垚",
        status: 1,
        uploadTime: "2024/02/12 12:40:12",
        key: 1
    },{
        title: "莫光芮",
        status: 0,
        uploadTime: "2024/02/12 12:33:30",
        key: 2
    }
];

export const TaskRecord = LibAppView.withService<ITaskDetailProps>({
    reqEndPoints: [{
        endPoint: "setting.studentList",
        name: "studentList",
        uri: {
            name: utils.getQuery("name") ?? "没有任务"
        }
    }]
})((props) => {
    const [ studentList, setStudentList ] = useState(userList);
    const [ taskName ] = useState(() => utils.getQuery("name") ?? props.task ?? "没有任务");
    const fileRef = useRef<HTMLInputElement>(null);
    const [ uploadTemp ] = useState({
        file: null,
        data: null
    });
    const onUpload = useCallback((data: any) => {
        if(fileRef.current) {
            uploadTemp.data = data;
            fileRef.current.click();
        }
    }, [taskName]);
    const filterList = useMemo(() => studentList.map((item) => ({text: item.title, value:item.title})), [studentList]);
    const columns = useMemo<any[]>(() =>([
        { title: "操作", "dataIndex": "status", render: (status: number, data: any) => {
            return <Button onClick={() => onUpload(data)} type="dashed">上传</Button>
        }},
        {
            title: "学生姓名",
            dataIndex: "title", 
            filterSearch: true,
            filterMode: "menu",
            filters: filterList,
            onFilter: (value: any, record: any): any => record.title.indexOf(value) >= 0
        },
        { title: "状态", dataIndex: "status", render: (status: any) => {
            const statusText = /^1$/.test(status) ? "已上传" : "未上传";
            const statusStyle = /^1$/.test(status) ? { color: "green" } : { color: "red" };
            return <span style={statusStyle}>{statusText}</span>
        } },
        { title: "完成时间", dataIndex: "uploadTime", render: (uploadTime: number) => {
            return <span>{uploadTime ?? "未完成"}</span>
        }},
        { title: "任务", dataIndex: "activity", render: (name: string) =>{
            return <span>{name ?? "没有任务"}</span>
        }}
    ]), [filterList]);
    const app = LibAppView.useApp();
    const antApp = App.useApp();
    const finalStudentList = useMemo(() => {
        const newStudentList = [...studentList];
        newStudentList.sort((v) => v.status > 0 ? 1 : -1);
        return newStudentList;
    }, [studentList]);
    const uploadedCount = useMemo(() => {
        let uploadCount = 0;
        let unUploadCount = 0;
        studentList.forEach((item) => {
            if(item.status > 0) {
                uploadCount += 1;
            } else {
                unUploadCount += 1;
            }
        });
        return {
            uploaded: uploadCount,
            unUploaded: unUploadCount
        }
    }, [studentList]);
    const refresh = useCallback(() => {
        app.serviceApi.send({
            endPoint: "setting.studentList",
            uri: {
                name: encodeURIComponent(taskName)
            }
        }).then(({ data }: any) => {
            setStudentList(data);
        }).catch((err) => {
            antApp.message.error(err.message);
        });
    }, [taskName]);
    const onUploadFileChange = useCallback((event: React.ChangeEvent<HTMLInputElement>) => {
        const fileData = event.target.files?.[0];
        if(fileData) {
            const formData = new FormData();
            const userData: any = uploadTemp.data || {};
            console.log(userData);
            formData.append("file", fileData);
            props.withServiceApi.send({
                endPoint: "setting.uploadFile",
                data: formData,
                header: {
                    UploadAction: "StudentRecord",
                    StudentRecordTask: encodeURIComponent(userData.activity),
                    StudentName: encodeURIComponent(userData.title)
                },
                isBinary: true
            }).then(() => {
                antApp.message.success("文件上传成功");
                refresh();
            }).catch((err) => {
                antApp.message.error("文件上传失败：" + err.message);
            });
        }
    }, [uploadTemp, refresh])
    useEffect(() => {
        if(props.responseData.afterApiResponse) {
            setStudentList((props.responseData as any).studentList?.data ?? []);
        }
    }, [props.responseData]);
    useEffect(() => {
        !utils.isEmpty(taskName) && refresh();
    }, [refresh,taskName]);
    return (
        <Card>
            <h2>{taskName ?? "任务数据"}</h2>
            <label><span style={{color: "green"}}>已上传({uploadedCount.uploaded})</span>, <span style={{color: "red"}}>未上传({uploadedCount.unUploaded})</span></label>
            <Divider />
            <section style={{overflowX: "auto"}}>
                <Table style={{minWidth: 600}} columns={columns} dataSource={finalStudentList}/>
            </section>
            
            <input type="file" ref={fileRef} style={{height: 1, zIndex: -1, opacity: 0}} onChange={onUploadFileChange}/>
        </Card>
    );
});

